package com.book.util;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ResourceBundle;

import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.delete.DeleteRequestBuilder;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



public class ElasticsearchUtil {

	private static final Logger log = LoggerFactory.getLogger(ElasticsearchUtil.class);
    private volatile static TransportClient client = null;  	
	
    private ElasticsearchUtil() {
	}

	@SuppressWarnings("resource")
	public static TransportClient getClient() {  
        if(client==null){  
            synchronized (ElasticsearchUtil.class) {
            	try {
					if(client==null){  
				    	ResourceBundle bundle = ResourceBundle.getBundle("elasticsearch");
				    	String host = bundle.getString("elasticsearch.host");
				    	int port = Integer.parseInt(bundle.getString("elasticsearch.port"));
				    	String clusterName = bundle.getString("elasticsearch.cluster.name");
						System.out.println(clusterName);
					    Settings settings = Settings.builder().put("cluster.name", clusterName)  
					            .put("client.transport.sniff", true)//自动嗅探整个集群的状态，把集群中其它机器的ip地址加到客户端中
					            .build();
					    client = new PreBuiltTransportClient(settings)
					    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host), port)); 
					}
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}
			}
        }  
        return client; 
    }	
	
    public static int index(String indexName, String typeName, String id, String source){
//    	log.info("indexName:"+indexName+"------typeName:"+typeName+"-----id:"+id+"-----source:"+source);
    	@SuppressWarnings("deprecation")
		IndexResponse response = ElasticsearchUtil.getClient().prepareIndex(indexName, typeName, id)
    			.setSource(source)
    			.get();
    	return response.status().getStatus();
    }	
   
    public static int delete(String indexName,String typeName,String id){
    	DeleteResponse deleteResponse  = ElasticsearchUtil.getClient().prepareDelete(indexName, typeName, id).get();
		return deleteResponse.status().getStatus();
    }

	public static void main(String[] args) {
		GetResponse response = ElasticsearchUtil.getClient().prepareGet("book", "book", "68b1af9ed1db43658b3b22cb9119b018").get();
        log.info(JSON.toJSONString(response.getSource()));
    }
}
